package dk.sdu.flexibus.addresssuggestor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;

public class ReverseGeocodingTask extends AsyncTask<Location, Void, ArrayList<String>> {
	Context context;
	AddressSuggester resultListener;

	public ReverseGeocodingTask(Context context, AddressSuggester listener) {
		super();
		this.context = context;
		this.resultListener = listener;
	}

	@Override
	protected ArrayList<String> doInBackground(Location... params) {
		Geocoder geocoder = new Geocoder(context, Locale.getDefault());
		
		ArrayList<String> addressesStrings = new ArrayList<String>();
		
		Location loc = params[0];
		List<Address> addresses = null;
		try {
			addresses = geocoder.getFromLocation(loc.getLatitude(),
					loc.getLongitude(), 1);
		} catch (IOException e) {
		}
		if (addresses != null && addresses.size() > 0) {
			for (Address address : addresses) {
				// Format the first line of address (if available), city,
				// and country name.
				String addressText = String.format(
						"%s, %s, %s",
						address.getMaxAddressLineIndex() > 0 ? address
								.getAddressLine(0) : "", address
								.getLocality(), address.getCountryName());
				addressesStrings.add(addressText);
			}
		}
		return addressesStrings;
	}

	@Override
	protected void onPostExecute(ArrayList<String> result) {
		super.onPostExecute(result);
		if(!result.isEmpty()){
			resultListener.notifySuggestionListeners(result);
		}
	}
}
